import React, { useEffect, useState } from 'react'
import {
    Text,
    View,
    Button,
    TouchableOpacity,
    SafeAreaView,
    Dimensions,
    Alert,
    FlatList,
    Image,
    ScrollView,
    TextInput,
} from 'react-native'
import Icon from 'react-native-vector-icons/FontAwesome';
import { TfiLayout } from "react-icons/tfi";
import { useNavigation, useRoute } from '@react-navigation/native'
import AsyncStorage from '@react-native-async-storage/async-storage';
import { createStackNavigator } from '@react-navigation/stack';

const getAvatarUrl = (profile_picture) => {
    if (!profile_picture) return require('../assets/default_avatar.png');
    if (profile_picture.startsWith('http')) return { uri: profile_picture };
    // 自动补全为绝对路径
    return { uri: `http://124.222.104.145:8003${profile_picture}` };
};

const BookContent = () => {
    const navigation = useNavigation();
    const route = useRoute();
    const { width: screenWidth, height: screenHeight } = Dimensions.get('window');
    const { bookId } = route.params || {};
    const [bookDetail, setBookDetail] = useState(null);
    const [loading, setLoading] = useState(true);
    const [isLogin, setIsLogin] = useState(false);

    const [isCollapsed, setCollapsed] = useState(true);

    useEffect(() => {
        const loadToken = async () => {
            const token = await AsyncStorage.getItem('authToken');
            if (token) setIsLogin(true);
        };
        loadToken();
    }, []);

    useEffect(() => {
        if (!bookId) return;
        const fetchBookDetail = async () => {
            try {
                const response = await fetch(`http://124.222.104.145:8003/book/books/${bookId}`);
                const data = await response.json();
                setBookDetail(data);
                setMenuList(data.chapters || []);
            } catch (error) {
                console.error('获取图书详情失败:', error);
            } finally {
                setLoading(false);
            }
        };
        fetchBookDetail();
    }, [bookId]);

    const [isopenMenu, setOpenMenu] = useState(false);
    const [isopenComments, setOpenComments] = useState(false);

    const [menuList, setMenuList] = useState([]);

    const addBook = async () => {
        if (!isLogin) {
            Alert.alert(
                '请先登录',
                '您还没有登录，请先登录。',
                [
                    { text: '取消', style: 'cancel' },
                    { text: '去登录', onPress: () => navigation.navigate('My', { screen: 'LoginPage' }) }
                ]
            );
            return;
        }
        try {
            const token = await AsyncStorage.getItem('authToken');
            const response = await fetch(`http://124.222.104.145:8003/book/books/${bookId}/add-to-shelf/`, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    book_id: bookId,
                    classification: '默认分类',
                    is_public: false
                }),
            });
            const data = await response.json();
            if (response.ok && data.success) {
                Alert.alert('成功', data.message || '添加成功');
            } else {
                Alert.alert('失败', data.message || '添加失败');
            }
        } catch (error) {
            Alert.alert('错误', '网络请求失败');
        }
    };

    useEffect(() => {
        if (!bookId) return;
        const fetchComments = async () => {
            try {
                const token = await AsyncStorage.getItem('authToken');
                const response = await fetch(`http://124.222.104.145:8003/comments/books/${bookId}/comments/`, {
                    headers: { 'Authorization': `Bearer ${token}` }
                });
                const data = await response.json();
                console.log('评论接口返回', data);
                if (Array.isArray(data)) {
                    setComments(data);
                } else if (Array.isArray(data.comments)) {
                    setComments(data.comments);
                } else {
                    setComments([]);
                }
            } catch (e) {
                setComments([]);
            }
        };
        fetchComments();
    }, [bookId, isopenComments]);

    const [comments, setComments] = useState([]);
    const [showCommentInput, setShowCommentInput] = useState(false);
    const [commentContent, setCommentContent] = useState('');

    const [replyingCommentId, setReplyingCommentId] = useState(null);
    const [replyContent, setReplyContent] = useState('');

    // 写评论按钮统一处理
    const handleWriteComment = () => {
        if (!isLogin) {
            Alert.alert(
                '请先登录',
                '您还没有登录，请先登录。',
                [
                    { text: '取消', style: 'cancel' },
                    { text: '去登录', onPress: () => navigation.navigate('My', { screen: 'LoginPage' }) }
                ]
            );
            return;
        }
        setShowCommentInput(true);
    };

    const replyToComment = async (bookId, commentId, replyContent) => {
        if (!replyContent.trim()) {
            Alert.alert('回复内容不能为空');
            return;
        }
        const token = await AsyncStorage.getItem('authToken');
        const response = await fetch(`http://124.222.104.145:8003/comments/books/${bookId}/comments/${commentId}/reply/`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ content: replyContent }),
        });
        const data = await response.json(); 
        // 处理 data
    };

    if (loading) {
        return <Text>加载中...</Text>;
    }
    if (!bookDetail) {
        return <Text>未找到图书信息</Text>;
    }

    console.log('comments 渲染', comments);

    return (
        <SafeAreaView style={{ flex: 1 }}>
            {/* 顶部返回条 */}
            <View
                style={{
                    paddingBlock: 0,
                    paddingHorizontal: 30,
                    paddingTop: 30,
                    paddingRight: 50,
                    backgroundColor: "#f2f2f2",
                }}>
                <View style={{ flexDirection: "row", justifyContent: "space-between" }}>
                    <TouchableOpacity onPress={() => navigation.goBack()} >
                        <Icon name="angle-left" size={30} color="#000" />
                    </TouchableOpacity>
                </View>
            </View>

            {/* <ScrollView> 不能在其中嵌套flatlist */}

            <View style={{ backgroundColor: "#f2f2f2", paddingTop: 1, minHeight: screenHeight - 500 }}>
                {/* 上方内容 */}
                <View style={{ flexDirection: "row", justifyContent: "space-between", paddingHorizontal: 30, padding: 20 }}>
                    <View style={{
                        width: 0.31 * screenWidth,
                        height: 0.20 * screenHeight,
                        backgroundColor: "rgb(255, 255, 255)",
                        borderRadius: 10,
                        justifyContent: "center",
                        alignItems: "center",
                        boxShadow: '-5.5px 4px 3.4px 0px rgba(142, 142, 142, 0.2)',
                    }}>
                        <Image source={{ uri: bookDetail.image }} style={{ width: 100, height: 140, borderRadius: 8 }} />
                    </View>
                    <View style={{
                        width: 0.48 * screenWidth,
                        height: 0.20 * screenHeight,
                        backgroundColor: "rgba(195, 195, 195, 0)",
                        borderRadius: 10,
                        padding: 0,
                        paddingTop: 5,
                        overflow: 'visible',
                    }}>
                        <View style={{ marginBottom: 5 }}>
                            <Text numberOfLines={1} ellipsizeMode="tail"
                                style={{ fontSize: 18, lineHeight: 40, flexShrink: 1, alignSelf: 'flex-start' }}
                            >{bookDetail.title}</Text>
                            <Text numberOfLines={1} ellipsizeMode="tail"
                                style={{ fontSize: 13, lineHeight: 24, flexShrink: 1, alignSelf: 'flex-start' }}
                            >作者：{bookDetail.author}</Text>
                            <Text numberOfLines={1} ellipsizeMode="tail"
                                style={{ fontSize: 13, lineHeight: 24, flexShrink: 1, alignSelf: 'flex-start' }}
                            >分类：{bookDetail.category}</Text>
                            <Text numberOfLines={1} ellipsizeMode="tail"
                                style={{ fontSize: 13, lineHeight: 24, flexShrink: 1, alignSelf: 'flex-start' }}
                            >状态：{bookDetail.status}</Text>
                            <Text numberOfLines={1} ellipsizeMode="tail"
                                style={{
                                    fontSize: 13,
                                    lineHeight: 30,
                                    flexShrink: 1,
                                    alignSelf: 'flex-start',
                                    width: '100%'
                                }}
                            >最近更新：{bookDetail.update_time?.split('T')[0] || bookDetail.update_time}</Text>

                            <TouchableOpacity
                                onPress={() => setCollapsed(!isCollapsed)}
                                style={{
                                    flexDirection: 'row',
                                    alignItems: 'center',
                                    marginBottom: isCollapsed ? 0 : 10,
                                }}>
                                <Text style={{ fontSize: 14, fontWeight: 'bold', color: '#333' }}>内容简介  </Text>
                                <Icon
                                    name={isCollapsed ? "chevron-down" : "chevron-up"}
                                    size={14}
                                    color="rgb(69, 110, 61)"
                                    style={{ marginLeft: 8 }}
                                />
                            </TouchableOpacity>



                        </View>
                    </View>
                </View>

                {/* 书籍简介 */}
                {!isCollapsed && (
                    <View style={{
                        backgroundColor: "#fff",
                        borderRadius: 10,
                        margin: 10,
                        padding: 15,
                        marginTop: 5,
                    }}>
                        <View style={{
                            flexDirection: 'row',
                            alignItems: 'center',
                            marginBottom: 10,
                        }}>
                            <Text style={{ fontSize: 16, fontWeight: 'bold', color: '#333' }}>内容简介</Text>
                            <Icon name="book" size={14} color="rgb(69, 110, 61)" style={{ marginLeft: 8 }} />
                        </View>
                        <ScrollView
                            style={{
                                maxHeight: 120,
                                backgroundColor: 'rgba(250, 250, 250, 0.5)',
                                borderRadius: 8,
                                padding: 10,
                            }}
                            showsVerticalScrollIndicator={false}
                        >
                            <Text style={{
                                fontSize: 14,
                                lineHeight: 22,
                                color: '#666',
                                textAlign: 'justify',
                            }}>
                                {bookDetail.description || '暂无简介'}
                            </Text>
                            <View style={{ height: 10 }}></View>
                        </ScrollView>
                    </View>



                )}
                {/* 中部区域 */}
                <View style={{
                    backgroundColor: "rgb(255,255,255)",
                    borderRadius: 0,
                    borderTopLeftRadius: 30,
                    borderTopRightRadius: 30,
                    height: 0.6 * screenHeight,
                    padding: 15,
                    paddingHorizontal: 20,
                }}>

                    {!isopenComments ? (
                        !isopenMenu ? (
                            <View style={{
                                backgroundColor: "#f2f2f2",
                                flex: 0.75,
                                marginBlock: 10,
                                borderTopLeftRadius: 30,
                                borderTopRightRadius: 30,
                                padding: 25,
                                paddingTop: 15,
                                paddingBottom: 15,
                                // Shadow properties
                                boxShadow: '-4px -3px 3.5px -2px rgba(142, 142, 142, 0.51)',
                            }}>
                                <View style={{
                                    flexDirection: "row",
                                    justifyContent: "space-between",
                                }}>
                                    <View style={{ flexDirection: "row", }}>
                                        <Text style={{ fontSize: 16 }}>
                                            目录
                                        </Text>
                                        <View style={{ justifyContent: "center", alignItems: "center", marginLeft: 5, marginTop: 4 }}>
                                            {/* <TfiLayout /> */}
                                            <Icon name="columns" size={14} color="rgb(69, 110, 61)" />
                                        </View>
                                    </View>
                                    {/* <Text style={{ fontSize: 10, color: "#B3D9D9" }}>共{menuList.length}章</Text> */}
                                    <View style={{ justifyContent: "center", alignItems: "center", }}>
                                        <TouchableOpacity onPress={() => setOpenMenu(!isopenMenu)}>
                                            <Icon name="angle-right" size={15} color="rgba(69, 110, 61, 0.8)" />
                                        </TouchableOpacity>
                                    </View>
                                </View>
                                <View style={{ flex: 1, marginTop: 5 }}>
                                    <FlatList
                                        data={menuList.slice(0, 4)}  // 只取前4条数据
                                        scrollEnabled={false}        // 不启用滚动功能
                                        showsVerticalScrollIndicator={false}  // 隐藏滚动条
                                        keyExtractor={item => item.id.toString()}
                                        contentContainerStyle={{ paddingBottom: 10 }}
                                        renderItem={({ item }) => (
                                            <TouchableOpacity
                                                onPress={() => {
                                                    if (!isLogin) {
                                                        Alert.alert(
                                                            '请先登录',
                                                            '您还没有登录，请先登录。',
                                                            [
                                                                { text: '取消', style: 'cancel' },
                                                                { text: '去登录', onPress: () => navigation.navigate('My', { screen: 'LoginPage' }) }
                                                            ]
                                                        );
                                                        return;
                                                    }
                                                    navigation.navigate('BookReading', {
                                                        bookId: bookId,
                                                        chapterId: item.id,
                                                        chapterOrder: item.order
                                                    });
                                                }}
                                                style={{
                                                    flexDirection: 'row',
                                                    justifyContent: 'space-between',
                                                    paddingVertical: 8,
                                                    paddingHorizontal: 5,
                                                    borderColor: 'rgba(200, 200, 200, 0.3)',
                                                    alignItems: 'center'
                                                }}
                                            >
                                                <View style={{ flexDirection: 'row', flex: 1 }}>
                                                    <View style={{ flexDirection: 'row', marginRight: 10 }}>
                                                        <Text style={{ fontSize: 12, fontWeight: 'bold' }}>·</Text>
                                                        <Text style={{ fontSize: 12, color: '#333' }}> 第{item.order + 1}章</Text>
                                                    </View>
                                                    <Text style={{ fontSize: 12, color: '#336666', flex: 1 }} numberOfLines={1}>{item.title}</Text>
                                                </View>
                                            </TouchableOpacity>
                                        )}
                                    />
                                </View>
                            </View>
                        ) : (
                            <View style={{
                                backgroundColor: "#f2f2f2",
                                flex: 1,
                                marginBlock: 10,
                                borderTopLeftRadius: 30,
                                borderTopRightRadius: 30,
                                borderBottomLeftRadius: 30,
                                borderBottomRightRadius: 30,
                                padding: 25,
                                paddingTop: 15,
                                paddingBottom: 15,
                                // Shadow properties
                                boxShadow: '-4px -3px 3.5px -2px rgba(142, 142, 142, 0.51)',
                            }}>
                                <View style={{
                                    flexDirection: "row",
                                    justifyContent: "space-between",
                                    // alignItems: 'center'
                                }}>
                                    <View style={{
                                        flexDirection: "row",
                                        // justifyContent: "space-between", 
                                    }}>
                                        <View style={{ justifyContent: "center", alignItems: "center", marginRight: 25 }}>
                                            <TouchableOpacity onPress={() => setOpenMenu(!isopenMenu)}>
                                                <Icon name="angle-left" size={20} color="rgba(69, 110, 61, 0.8)" />
                                            </TouchableOpacity>
                                        </View>
                                        <View style={{ flexDirection: "row", }}>
                                            <Text style={{ fontSize: 16 }}>
                                                目录
                                            </Text>
                                            <View style={{ justifyContent: "center", alignItems: "center", marginLeft: 5, marginTop: 4 }}>
                                                {/* <TfiLayout /> */}
                                                <Icon name="columns" size={14} color="rgb(69, 110, 61)" />
                                            </View>
                                        </View>
                                    </View>

                                    <Text style={{ fontSize: 10, color: "#B3D9D9" }}>共{menuList.length}章</Text>


                                </View>
                                <View style={{ flex: 1, marginTop: 10, maxHeight: 0.45 * screenHeight }}>
                                    <FlatList
                                        data={menuList}
                                        keyExtractor={item => item.id.toString()}
                                        showsVerticalScrollIndicator={true}
                                        contentContainerStyle={{ paddingBottom: 20 }}
                                        renderItem={({ item }) => (
                                            <TouchableOpacity
                                                onPress={() => {
                                                    if (!isLogin) {
                                                        Alert.alert(
                                                            '请先登录',
                                                            '您还没有登录，请先登录。',
                                                            [
                                                                { text: '取消', style: 'cancel' },
                                                                { text: '去登录', onPress: () => navigation.navigate('My', { screen: 'LoginPage' }) }
                                                            ]
                                                        );
                                                        return;
                                                    }
                                                    navigation.navigate('BookReading', {
                                                        bookId: bookId,
                                                        chapterId: item.id,
                                                        chapterOrder: item.order
                                                    });
                                                }}
                                                style={{
                                                    flexDirection: 'row',
                                                    justifyContent: 'flex-start',
                                                    paddingVertical: 10,
                                                    paddingHorizontal: 5,
                                                    borderBottomWidth: 1,
                                                    borderColor: 'rgba(125, 125, 125, 0.3)',
                                                }}
                                            >
                                                <View style={{ flexDirection: 'row', flex: 1 }}>
                                                    <View style={{ flexDirection: 'row', marginRight: 10 }}>
                                                        <Text style={{ fontSize: 12, fontWeight: 'bold' }}>·</Text>
                                                        <Text style={{ fontSize: 12, color: '#333' }}> 第{item.order + 1}章</Text>
                                                    </View>
                                                    <Text style={{ fontSize: 14, color: '#336666', flex: 1 }} numberOfLines={1}>{item.title}</Text>
                                                </View>
                                            </TouchableOpacity>
                                        )}
                                    />
                                </View>
                            </View>
                        )
                    )
                        :
                        (
                            <></>
                        )
                    }


                    {!isopenMenu ? (
                        !isopenComments ? (
                            <View style={{
                                backgroundColor: "#f2f2f2",
                                flex: 1.25,
                                marginBlock: 10,
                                borderBottomLeftRadius: 30,
                                borderBottomRightRadius: 30,
                                padding: 25,
                                paddingTop: 15,
                                // Shadow properties
                                boxShadow: '-4px -3px 3.5px -2px rgba(142, 142, 142, 0.51)', // Optional: adds a subtle shadow
                            }}>
                                <View style={{
                                    flexDirection: "row",
                                    justifyContent: "space-between",
                                    alignItems: 'center',
                                    marginBottom: 10,
                                }}>
                                    <View style={{ flexDirection: "row", alignItems: 'center' }}>
                                        <Text style={{ fontSize: 16, color: '#333', fontWeight: '500' }}>
                                            书籍评论
                                        </Text>
                                        <View style={{ marginLeft: 5, backgroundColor: '#e8e8e8', paddingHorizontal: 8, paddingVertical: 2, borderRadius: 10 }}>
                                            <Text style={{ fontSize: 12, color: '#666' }}>{comments.length}</Text>
                                        </View>
                                    </View>
                                    <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                                        <TouchableOpacity onPress={handleWriteComment} style={{
                                            backgroundColor: 'rgba(69, 110, 61, 0.1)',
                                            padding: 5,
                                            borderRadius: 5,
                                            flexDirection: 'row',
                                            alignItems: 'center',
                                            marginRight: 8
                                        }}>
                                            <Icon name="plus" size={12} color="rgba(69, 110, 61, 0.8)" />
                                            <Text style={{ fontSize: 12, color: 'rgba(69, 110, 61, 0.8)', marginLeft: 3 }}>写评论</Text>
                                        </TouchableOpacity>
                                        <View style={{ marginLeft: 8 }}/>
                                        <TouchableOpacity onPress={() => setOpenComments(true)}>
                                            <Icon name="angle-right" size={18} color="#888" />
                                        </TouchableOpacity>
                                    </View>
                                </View>
                                <View style={{ flex: 1 }}>
                                    {comments.length === 0 ? (
                                        <Text style={{ color: '#999', textAlign: 'center' }}>暂无评论</Text>
                                    ) : (
                                        <FlatList
                                            data={comments}
                                            keyExtractor={item => item.id.toString()}
                                            renderItem={({ item }) => (
                                                <View style={{ flexDirection: 'row', marginBottom: 15, backgroundColor: '#fafafa', borderRadius: 8, padding: 10 }}>
                                                    {/* 头像 */}
                                                    <Image
                                                        source={getAvatarUrl(item.user?.profile_picture)}
                                                        style={{ width: 36, height: 36, borderRadius: 18, marginRight: 10, backgroundColor: '#eee' }}
                                                    />
                                                    <View style={{ flex: 1 }}>
                                                        <Text style={{ fontWeight: 'bold' }}>{item.user?.username || item.user}</Text>
                                                        <Text style={{ color: '#333', marginVertical: 5 }}>{item.content}</Text>
                                                        <Text style={{ color: '#aaa', fontSize: 12 }}>{item.created_at?.replace('T', ' ').slice(0, 16)}</Text>
                                                        {/* 回复按钮 */}
                                                        <TouchableOpacity
                                                            onPress={() => {
                                                                if (!isLogin) {
                                                                    Alert.alert(
                                                                        '请先登录',
                                                                        '您还没有登录，请先登录。',
                                                                        [
                                                                            { text: '取消', style: 'cancel' },
                                                                            { text: '去登录', onPress: () => navigation.navigate('My', { screen: 'LoginPage' }) }
                                                                        ]
                                                                    );
                                                                    return;
                                                                }
                                                                setReplyingCommentId(item.id);
                                                            }}
                                                            style={{
                                                                backgroundColor: '#f4f7f3',
                                                                borderRadius: 8,
                                                                paddingHorizontal: 12,
                                                                paddingVertical: 4,
                                                                marginTop: 6,
                                                                alignSelf: 'flex-start'
                                                            }}
                                                        >
                                                            <Text style={{ color: '#458e3d', fontSize: 14 }}>回复</Text>
                                                        </TouchableOpacity>
                                                        {replyingCommentId === item.id && (
                                                            <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 8 }}>
                                                                <TextInput
                                                                    value={replyContent}
                                                                    onChangeText={setReplyContent}
                                                                    placeholder="回复内容"
                                                                    style={{
                                                                        flex: 1,
                                                                        borderWidth: 1,
                                                                        borderColor: '#e0e0e0',
                                                                        borderRadius: 20,
                                                                        paddingHorizontal: 12,
                                                                        paddingVertical: 6,
                                                                        marginRight: 8,
                                                                        backgroundColor: '#fff'
                                                                    }}
                                                                />
                                                                <TouchableOpacity
                                                                    style={{
                                                                        backgroundColor: '#458e3d',
                                                                        borderRadius: 20,
                                                                        paddingHorizontal: 18,
                                                                        paddingVertical: 7,
                                                                        marginRight: 8
                                                                    }}
                                                                    onPress={async () => {
                                                                        if (!replyContent.trim()) return;
                                                                        try {
                                                                            const token = await AsyncStorage.getItem('authToken');
                                                                            const response = await fetch(`http://124.222.104.145:8003/comments/books/${bookId}/comments/${item.id}/reply/`, {
                                                                                method: 'POST',
                                                                                headers: {
                                                                                    'Authorization': `Bearer ${token}`,
                                                                                    'Content-Type': 'application/json',
                                                                                },
                                                                                body: JSON.stringify({ content: replyContent }),
                                                                            });
                                                                            if (response.ok) {
                                                                                setReplyContent('');
                                                                                setReplyingCommentId(null);
                                                                                navigation.replace('BookContent', { bookId });
                                                                            } else {
                                                                                Alert.alert('失败', '回复失败');
                                                                            }
                                                                        } catch (e) {
                                                                            Alert.alert('错误', '网络请求失败');
                                                                        }
                                                                    }}
                                                                >
                                                                    <Text style={{ color: '#fff', fontWeight: 'bold' }}>提交</Text>
                                                                </TouchableOpacity>
                                                                <TouchableOpacity
                                                                    style={{
                                                                        backgroundColor: '#e0e0e0',
                                                                        borderRadius: 20,
                                                                        paddingHorizontal: 18,
                                                                        paddingVertical: 7
                                                                    }}
                                                                    onPress={() => setReplyingCommentId(null)}
                                                                >
                                                                    <Text style={{ color: '#333' }}>取消</Text>
                                                                </TouchableOpacity>
                                                            </View>
                                                        )}
                                                        {/* 嵌套显示回复列表 */}
                                                        {item.replies && item.replies.length > 0 && (
                                                            <View style={{ marginTop: 10, marginLeft: 15 }}>
                                                                {item.replies.map(reply => (
                                                                    <View key={reply.id} style={{ flexDirection: 'row', marginBottom: 8, backgroundColor: '#f4f4f4', borderRadius: 6, padding: 7 }}>
                                                                        <Image
                                                                            source={getAvatarUrl(reply.user?.profile_picture)}
                                                                            style={{ width: 28, height: 28, borderRadius: 14, marginRight: 8, backgroundColor: '#eee' }}
                                                                        />
                                                                        <View style={{ flex: 1 }}>
                                                                            <Text style={{ fontWeight: 'bold', fontSize: 13 }}>{reply.user?.username || reply.user}</Text>
                                                                            <Text style={{ color: '#333', fontSize: 13, marginVertical: 2 }}>{reply.content}</Text>
                                                                            <Text style={{ color: '#aaa', fontSize: 11 }}>{reply.created_at?.replace('T', ' ').slice(0, 16)}</Text>
                                                                        </View>
                                                                    </View>
                                                                ))}
                                                            </View>
                                                        )}
                                                    </View>
                                                </View>
                                            )}
                                        />
                                    )}
                                </View>
                            </View>
                        ) : (
                            <View style={{
                                backgroundColor: "#f2f2f2",
                                flex: 1,
                                marginBlock: 10,
                                borderBottomLeftRadius: 30,
                                borderBottomRightRadius: 30,
                                borderTopLeftRadius: 30,
                                borderTopRightRadius: 30,
                                padding: 25,
                                paddingTop: 15,
                                // Shadow properties
                                boxShadow: '-4px -3px 3.5px -2px rgba(142, 142, 142, 0.51)', // Optional: adds a subtle shadow
                            }}>
                                <View style={{
                                    flexDirection: "row",
                                    alignItems: 'center',
                                    marginBottom: 15,
                                }}>
                                    <TouchableOpacity
                                        onPress={() => setOpenComments(false)}
                                        style={{ padding: 5, marginRight: 10 }}
                                    >
                                        <Icon name="angle-left" size={20} color="#333" />
                                    </TouchableOpacity>
                                    <Text style={{ fontSize: 16, color: '#333', fontWeight: '500' }}>
                                        书籍评论
                                    </Text>
                                    <View style={{ marginLeft: 5, backgroundColor: '#e8e8e8', paddingHorizontal: 8, paddingVertical: 2, borderRadius: 10 }}>
                                        <Text style={{ fontSize: 12, color: '#666' }}>{comments.length}</Text>
                                    </View>
                                </View>
                                <View style={{ flex: 1 }}>
                                    {comments.length === 0 ? (
                                        <View style={{ alignItems: 'center', justifyContent: 'center', paddingVertical: 30 }}>
                                            <Icon name="comments-o" size={32} color="#ccc" />
                                            <Text style={{ fontSize: 14, color: '#999', marginTop: 10 }}>暂无评论，快来发表第一条评论吧</Text>
                                            <TouchableOpacity
                                                style={{
                                                    backgroundColor: 'rgba(69, 110, 61, 0.1)',
                                                    paddingHorizontal: 15,
                                                    paddingVertical: 8,
                                                    borderRadius: 20,
                                                    marginTop: 15,
                                                    flexDirection: 'row',
                                                    alignItems: 'center'
                                                }}
                                                onPress={handleWriteComment}
                                            >
                                                <Icon name="edit" size={14} color="rgba(69, 110, 61, 0.8)" />
                                                <Text style={{ fontSize: 14, color: 'rgba(69, 110, 61, 0.8)', marginLeft: 5 }}>写评论</Text>
                                            </TouchableOpacity>
                                        </View>
                                    ) : (
                                        <>
                                            <FlatList
                                                data={comments}
                                                keyExtractor={item => item.id.toString()}
                                                renderItem={({ item }) => (
                                                    <View style={{ flexDirection: 'row', marginBottom: 15, backgroundColor: '#fafafa', borderRadius: 8, padding: 10 }}>
                                                        {/* 头像 */}
                                                        <Image
                                                            source={getAvatarUrl(item.user?.profile_picture)}
                                                            style={{ width: 36, height: 36, borderRadius: 18, marginRight: 10, backgroundColor: '#eee' }}
                                                        />
                                                        <View style={{ flex: 1 }}>
                                                            <Text style={{ fontWeight: 'bold' }}>{item.user?.username || item.user}</Text>
                                                            <Text style={{ color: '#333', marginVertical: 5 }}>{item.content}</Text>
                                                            <Text style={{ color: '#aaa', fontSize: 12 }}>{item.created_at?.replace('T', ' ').slice(0, 16)}</Text>
                                                            {/* 回复按钮 */}
                                                            <TouchableOpacity
                                                                onPress={() => {
                                                                    if (!isLogin) {
                                                                        Alert.alert(
                                                                            '请先登录',
                                                                            '您还没有登录，请先登录。',
                                                                            [
                                                                                { text: '取消', style: 'cancel' },
                                                                                { text: '去登录', onPress: () => navigation.navigate('My', { screen: 'LoginPage' }) }
                                                                            ]
                                                                        );
                                                                        return;
                                                                    }
                                                                    setReplyingCommentId(item.id);
                                                                }}
                                                                style={{
                                                                    backgroundColor: '#f4f7f3',
                                                                    borderRadius: 8,
                                                                    paddingHorizontal: 12,
                                                                    paddingVertical: 4,
                                                                    marginTop: 6,
                                                                    alignSelf: 'flex-start'
                                                                }}
                                                            >
                                                                <Text style={{ color: '#458e3d', fontSize: 14 }}>回复</Text>
                                                            </TouchableOpacity>
                                                            {replyingCommentId === item.id && (
                                                                <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 8 }}>
                                                                    <TextInput
                                                                        value={replyContent}
                                                                        onChangeText={setReplyContent}
                                                                        placeholder="回复内容"
                                                                        style={{
                                                                            flex: 1,
                                                                            borderWidth: 1,
                                                                            borderColor: '#e0e0e0',
                                                                            borderRadius: 20,
                                                                            paddingHorizontal: 12,
                                                                            paddingVertical: 6,
                                                                            marginRight: 8,
                                                                            backgroundColor: '#fff'
                                                                        }}
                                                                    />
                                                                    <TouchableOpacity
                                                                        style={{
                                                                            backgroundColor: '#458e3d',
                                                                            borderRadius: 20,
                                                                            paddingHorizontal: 18,
                                                                            paddingVertical: 7,
                                                                            marginRight: 8
                                                                        }}
                                                                        onPress={async () => {
                                                                            if (!replyContent.trim()) return;
                                                                            try {
                                                                                const token = await AsyncStorage.getItem('authToken');
                                                                                const response = await fetch(`http://124.222.104.145:8003/comments/books/${bookId}/comments/${item.id}/reply/`, {
                                                                                    method: 'POST',
                                                                                    headers: {
                                                                                        'Authorization': `Bearer ${token}`,
                                                                                        'Content-Type': 'application/json',
                                                                                    },
                                                                                    body: JSON.stringify({ content: replyContent }),
                                                                                });
                                                                                if (response.ok) {
                                                                                    setReplyContent('');
                                                                                    setReplyingCommentId(null);
                                                                                    navigation.replace('BookContent', { bookId });
                                                                                } else {
                                                                                    Alert.alert('失败', '回复失败');
                                                                                }
                                                                            } catch (e) {
                                                                                Alert.alert('错误', '网络请求失败');
                                                                            }
                                                                        }}
                                                                    >
                                                                        <Text style={{ color: '#fff', fontWeight: 'bold' }}>提交</Text>
                                                                    </TouchableOpacity>
                                                                    <TouchableOpacity
                                                                        style={{
                                                                            backgroundColor: '#e0e0e0',
                                                                            paddingVertical: 8,
                                                                            paddingHorizontal: 22,
                                                                            borderRadius: 20,
                                                                        }}
                                                                        onPress={() => setReplyingCommentId(null)}
                                                                    >
                                                                        <Text style={{ color: '#333', fontSize: 15 }}>取消</Text>
                                                                    </TouchableOpacity>
                                                                </View>
                                                            )}
                                                            {/* 嵌套显示回复列表 */}
                                                            {item.replies && item.replies.length > 0 && (
                                                                <View style={{ marginTop: 10, marginLeft: 15 }}>
                                                                    {item.replies.map(reply => (
                                                                        <View key={reply.id} style={{ flexDirection: 'row', marginBottom: 8, backgroundColor: '#f4f4f4', borderRadius: 6, padding: 7 }}>
                                                                            <Image
                                                                                source={getAvatarUrl(reply.user?.profile_picture)}
                                                                                style={{ width: 28, height: 28, borderRadius: 14, marginRight: 8, backgroundColor: '#eee' }}
                                                                            />
                                                                            <View style={{ flex: 1 }}>
                                                                                <Text style={{ fontWeight: 'bold', fontSize: 13 }}>{reply.user?.username || reply.user}</Text>
                                                                                <Text style={{ color: '#333', fontSize: 13, marginVertical: 2 }}>{reply.content}</Text>
                                                                                <Text style={{ color: '#aaa', fontSize: 11 }}>{reply.created_at?.replace('T', ' ').slice(0, 16)}</Text>
                                                                            </View>
                                                                        </View>
                                                                    ))}
                                                                </View>
                                                            )}
                                                        </View>
                                                    </View>
                                                )}
                                            />
                                            {/* 评论详情弹窗底部写评论按钮 */}
                                            <TouchableOpacity
                                                style={{
                                                    backgroundColor: 'rgba(69, 110, 61, 0.1)',
                                                    paddingHorizontal: 15,
                                                    paddingVertical: 8,
                                                    borderRadius: 20,
                                                    marginTop: 10,
                                                    alignSelf: 'center',
                                                    flexDirection: 'row',
                                                    alignItems: 'center'
                                                }}
                                                onPress={handleWriteComment}
                                            >
                                                <Icon name="edit" size={14} color="rgba(69, 110, 61, 0.8)" />
                                                <Text style={{ fontSize: 14, color: 'rgba(69, 110, 61, 0.8)', marginLeft: 5 }}>写评论</Text>
                                            </TouchableOpacity>
                                        </>
                                    )}
                                </View>
                            </View>
                        )
                    ) : null}

                </View>
            </View>

            {/* 底部条 */}
            <View style={{
                backgroundColor: "rgb(255,255,255)",
                height: 80,
                flexDirection: "row",
                justifyContent: "space-around",
                flex: 1,
            }}>
                <View style={{
                    borderColor: 'rgba(200, 200, 200, 0.6)',
                    borderWidth: 0,
                    width: 0.33 * screenWidth,
                    height: 0.035 * screenHeight,
                    // backgroundColor: "rgb(230, 230, 230)",
                    borderRadius: 3,
                    justifyContent: "center",
                    alignItems: "center",
                }}>
                    <TouchableOpacity onPress={() => addBook()}>
                        <View style={{ flexDirection: "row", }}>
                            <Text style={{ fontSize: 15, color: "rgb(69, 110, 61)" }}>
                                加入书架
                            </Text>
                            <View style={{ justifyContent: "center", alignItems: "center", marginLeft: 5, marginTop: 4 }}>
                                {/* <TfiLayout /> */}
                                <Icon name="bookmark" size={14} color="rgba(69, 110, 61, 0.7)" />
                            </View>
                        </View>
                    </TouchableOpacity>
                </View>
                <View style={{
                    borderColor: 'rgba(200, 200, 200, 0.12)',
                    borderWidth: 1,
                    width: 0.33 * screenWidth,
                    height: 0.035 * screenHeight,
                    backgroundColor: "rgba(230, 230, 230, 0.87)",
                    borderRadius: 3,
                    justifyContent: "center",
                    alignItems: "center",
                }}>
                    <TouchableOpacity
                        onPress={() => {
                            if (menuList.length > 0) {
                                navigation.navigate('BookReading', {
                                    bookId: bookId,
                                    chapterId: menuList[0].id
                                });
                            } else {
                                Alert.alert('没有章节', '本书暂无章节，无法阅读');
                            }
                        }}
                    >
                        <Text style={{ fontSize: 15, color: "rgb(68, 102, 61)" }}>
                            立刻阅读
                        </Text>
                    </TouchableOpacity>
                </View>

            </View>

            {showCommentInput && (
                <View style={{
                    position: 'absolute', left: 0, right: 0, bottom: 0, backgroundColor: '#fff', padding: 15, borderTopWidth: 1, borderColor: '#eee'
                }}>
                    <TextInput
                        value={commentContent}
                        onChangeText={setCommentContent}
                        placeholder="请输入评论内容"
                        style={{ borderWidth: 1, borderColor: '#ccc', borderRadius: 8, padding: 8, marginBottom: 10 }}
                    />
                    <View style={{ flexDirection: 'row', justifyContent: 'flex-end', marginTop: 5 }}>
                        <TouchableOpacity
                            style={{
                                backgroundColor: '#458e3d',
                                paddingVertical: 8,
                                paddingHorizontal: 22,
                                borderRadius: 20,
                                marginRight: 10,
                            }}
                            onPress={async () => {
                                if (!commentContent.trim()) return;
                                try {
                                    const token = await AsyncStorage.getItem('authToken');
                                    const response = await fetch(`http://124.222.104.145:8003/comments/books/${bookId}/comments/`, {
                                        method: 'POST',
                                        headers: {
                                            'Authorization': `Bearer ${token}`,
                                            'Content-Type': 'application/json',
                                        },
                                        body: JSON.stringify({ content: commentContent }),
                                    });
                                    if (response.ok) {
                                        setShowCommentInput(false);
                                        setCommentContent('');
                                        navigation.replace('BookContent', { bookId });
                                    } else {
                                        Alert.alert('失败', '评论失败');
                                    }
                                } catch (e) {
                                    Alert.alert('错误', '网络请求失败');
                                }
                            }}
                        >
                            <Text style={{ color: '#fff', fontSize: 15, fontWeight: 'bold' }}>提交</Text>
                        </TouchableOpacity>
                        <TouchableOpacity
                            style={{
                                backgroundColor: '#e0e0e0',
                                paddingVertical: 8,
                                paddingHorizontal: 22,
                                borderRadius: 20,
                            }}
                            onPress={() => setShowCommentInput(false)}
                        >
                            <Text style={{ color: '#333', fontSize: 15 }}>取消</Text>
                        </TouchableOpacity>
                    </View>
                </View>
            )}

            {/* </ScrollView> */}
        </SafeAreaView>
    )
}

export default BookContent
